package com.zhiwang.planet.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import com.zhiwang.planet.R

class TimeLineFrameLayout(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {


    var lineWidth = 0

    var lineColor = 0

    var circleRadius = 0

    var circleColor = 0

    var painter = Paint(Paint.ANTI_ALIAS_FLAG)

    var bottomExtra = 0


    init {

        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.TimeLineFrameLayout)
        lineWidth = typeArray.getDimensionPixelSize(R.styleable.TimeLineFrameLayout_fl_line_width, 0)
        lineColor = typeArray.getColor(R.styleable.TimeLineFrameLayout_fl_line_color, Color.BLACK)
        circleColor = typeArray.getColor(R.styleable.TimeLineFrameLayout_fl_circle_color, Color.BLACK)
        circleRadius = typeArray.getDimensionPixelSize(R.styleable.TimeLineFrameLayout_fl_circle_radius, 0)
        bottomExtra = typeArray.getDimensionPixelSize(R.styleable.TimeLineFrameLayout_fl_bottom_extra,0)
        typeArray.recycle()
        painter.style = Paint.Style.FILL
    }


    override fun dispatchDraw(canvas: Canvas?) {
        val lineHeight = measuredHeight / 2f - circleRadius

        val left = circleRadius - lineWidth / 2f
        painter.color = lineColor
        if (headerVisible)
            canvas?.drawRect(left, 0f, left + lineWidth, lineHeight, painter)
        canvas?.drawRect(left, lineHeight + circleRadius * 2, left + lineWidth, measuredHeight.toFloat(), painter)
        painter.color = circleColor
        canvas?.drawCircle(circleRadius.toFloat(), lineHeight + circleRadius, circleRadius.toFloat(), painter)
        super.dispatchDraw(canvas)
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (bottomExtra != 0) {
            for (i in 0 until childCount) {
                val child = getChildAt(i)
                val lp = child.layoutParams as LayoutParams

                lp.topMargin = bottomExtra
                child.layoutParams = lp
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (bottomExtra > 0)
            setMeasuredDimension(measuredWidth, MeasureSpec.makeMeasureSpec(measuredHeight + bottomExtra, MeasureSpec.EXACTLY))
    }


    var headerVisible: Boolean = true
        set(value) {
            field = value
            postInvalidate()
        }

    override fun onViewAdded(child: View?) {
        super.onViewAdded(child)
    }

    override fun removeView(view: View?) {
        super.removeView(view)
    }

}